package cn.broadmax.boot.modules.sys.controller;


import cn.broadmax.boot.base.SuperController;
import cn.broadmax.boot.log.LogType;
import cn.broadmax.boot.log.SysLog;
import cn.broadmax.boot.modules.sys.entity.SysResource;
import cn.broadmax.boot.modules.sys.entity.SysUser;
import cn.broadmax.boot.api.ISystemBaseApi;
import cn.broadmax.boot.base.message.SResult;
import cn.broadmax.boot.base.model.LoginUser;
import cn.broadmax.boot.modules.sys.bean.SysLoginModel;
import cn.broadmax.boot.modules.sys.bean.SysResourceTree;
import cn.broadmax.boot.modules.sys.service.ISysResourceService;
import cn.broadmax.boot.modules.sys.service.ISysUserService;
import cn.broadmax.boot.util.JwtUtils;
import cn.broadmax.boot.util.PasswordUtils;
import cn.broadmax.boot.util.SAssert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jexx.crypto.DigestUtil;
import jexx.util.BooleanUtil;
import jexx.util.Console;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 登陆
 * </p>
 *
 * @author jexx
 * @since 2020-06-14
 */
@Slf4j
@Api(tags = "授权")
@Validated
@RestController
@RequestMapping("/auth")
public class AuthController extends SuperController {

    @Autowired
    private ISysResourceService sysResourceService;
    @Autowired
    private ISysUserService sysUserService;

    private final ISystemBaseApi systemBaseApi;

    public AuthController(ISystemBaseApi systemBaseApi) {
        this.systemBaseApi = systemBaseApi;
    }

    @SysLog(type = LogType.LOGIN, value = "用户登陆")
    @ApiOperation("用户登录")
    @PostMapping(value = "/login")
    public SResult<Object> login(@Validated @RequestBody SysLoginModel model){
        SAssert.hasText(model.getUsername(), "用户名不能为空");
        SAssert.hasText(model.getPassword(), "密码不能为空");
        String username = model.getUsername();
        String password = model.getPassword();

        SysUser user = sysUserService.dynamicFindSysUser(username);
        SAssert.notNull(user, "用户名不存在");
        SAssert.isTrue(BooleanUtil.isNotTrue(user.getLocked()), "用户已冻结");

        String pass1 = PasswordUtils.decrypt(user.getPassword(), user.getSalt());
        pass1 = DigestUtil.md5Hex(pass1);
        SAssert.isTrue(password.equals(pass1), "用户名或密码错误");

        LoginUser loginUser = systemBaseApi.getAppUserByUserId(user.getId());
        SAssert.notNull(loginUser, "用户不存在");
        SAssert.isTrue(BooleanUtil.isNotTrue(loginUser.getLocked()), "用户已冻结");

        Map<String, Object> response = new HashMap<>(2);
        String token = JwtUtils.generateToken(loginUser);
        response.put("token", token);
        response.put("user", loginUser);
        return SResult.ok("", response);
    }

    @SysLog(type = LogType.LOGIN, value = "用户登陆")
    @ApiOperation("用户登录并附带菜单")
    @PostMapping(value = "/loginWithMore")
    public SResult<Object> loginWithMore(@Validated @RequestBody SysLoginModel model){
        SAssert.hasText(model.getUsername(), "用户名不能为空");
        SAssert.hasText(model.getPassword(), "密码不能为空");
        String username = model.getUsername();
        String password = model.getPassword();

        SysUser user = sysUserService.dynamicFindSysUser(username);
        SAssert.notNull(user, "用户不存在");
        SAssert.isTrue(BooleanUtil.isNotTrue(user.getLocked()), "用户已冻结");

        String pass1 = PasswordUtils.decrypt(user.getPassword(), user.getSalt());
        pass1 = DigestUtil.md5Hex(pass1);
        SAssert.isTrue(password.equals(pass1), "用户名或密码错误");

        LoginUser loginUser = systemBaseApi.getAppUserByUserId(user.getId());
        SAssert.notNull(loginUser, "用户不存在");
        SAssert.isTrue(BooleanUtil.isNotTrue(loginUser.getLocked()), "用户已冻结");

        Map<String, Object> response = new HashMap<>(2);
        String token = JwtUtils.generateToken(loginUser);
        response.put("token", token);
        response.put("user", loginUser);

        List<SysResourceTree> resources = getMyResource(user.getId());
        response.put("menu", resources);
        return SResult.ok("", response);
    }

    @ApiOperation("获取当前登陆用户信息")
    @GetMapping(value = "/user/info")
    public SResult<Object> getUserInfo(){
        String userId = getAccountId();
        LoginUser loginUser = systemBaseApi.getAppUserByUserId(userId);
//        Console.log(loginUser);
        return SResult.ok("", loginUser);
    }

    @ApiOperation("获取当前登陆用户信息列表")
    @GetMapping(value = "/user/info/list")
    public SResult<List<LoginUser>> getUserInfoList(){
        String userId = getAccountId();
        LoginUser loginUser = systemBaseApi.getAppUserByUserId(userId);
        ArrayList<LoginUser> loginUsers = new ArrayList<>();
        loginUsers.add(loginUser);
        return SResult.ok("", loginUsers);
    }

    @ApiOperation("获取当前登陆用户导航")
    @GetMapping(value = "/user/nav")
    public SResult<Object> getUserNav(){
        String userId = getAccountId();
        List<SysResourceTree> resourceTree = getMyResource(userId);
        return SResult.ok("", resourceTree);
    }

    @ApiOperation("用户退出")
    @SysLog(value = "用户退出")
    @PostMapping(value = "/logout")
    public SResult<Object> logout(){
        return SResult.ok("", true);
    }

    private List<SysResourceTree> getMyResource(String userId){
        List<SysResource> resources = sysResourceService.getResourcesByUserId(userId);
        return SysResourceTree.buildResourceTree(resources);
    }

}
